#!/usr/bin/env node
// ================================================
// Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [2025-07-28]
// 修改范围声明：本次仅修改 utils/unified-config-cli.js
// (c) 2020-2025 ALYR.NET // 版权不可修改
// ================================================

const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const inquirer = require('inquirer');
const UnifiedConfigManager = require('../config/unified-config-manager');

/**
 * Builder.Alyr.Net 统一配置CLI工具
 * @class UnifiedConfigCLI
 * @description 提供交互式配置管理界面
 */
class UnifiedConfigCLI {
  constructor() {
    this.configManager = new UnifiedConfigManager();
    this.isRunning = false;
  }

  /**
   * 启动CLI界面
   */
  async start() {
    this.isRunning = true;
    
<<<<<<< Updated upstream
    console.log(chalk.blue.bold('\n🔧 Builder.Alyr.Net 统一配置管理器 v4.0'));
=======
    console.log(chalk.blue.bold('\n🔧 Builder.Alyr.Net 统一配置管理器 V4.2.1'));
>>>>>>> Stashed changes
    console.log(chalk.gray('一键修改自动同步所有配置\n'));
    
    // 显示当前配置摘要
    this.showConfigSummary();
    
    while (this.isRunning) {
      try {
        await this.showMainMenu();
      } catch (error) {
        console.log(chalk.red(`❌ 操作失败: ${error.message}`));
        await this.pressAnyKey();
      }
    }
  }

  /**
   * 显示配置摘要
   */
  showConfigSummary() {
    const summary = this.configManager.getConfigSummary();
    
    console.log(chalk.cyan('📊 当前配置摘要:'));
    console.log(chalk.white(`  项目: ${summary.project}`));
    console.log(chalk.white(`  版本: ${summary.version}`));
    console.log(chalk.white(`  支持语言: ${summary.languages.total} 种 (前端: ${summary.languages.frontend}, 后端: ${summary.languages.backend})`));
    console.log(chalk.white(`  支持框架: ${summary.frameworks.total} 个 (前端: ${summary.frameworks.frontend}, 后端: ${summary.frameworks.backend})`));
    console.log(chalk.white(`  启用功能: ${summary.features} 个`));
    console.log(chalk.gray(`  最后更新: ${new Date(summary.lastUpdated).toLocaleString()}\n`));
  }

  /**
   * 显示主菜单
   */
  async showMainMenu() {
    const choices = [
      { name: '🔄 一键同步所有配置', value: 'sync_all' },
      { name: '⚙️ 管理编程语言', value: 'manage_languages' },
      { name: '🚀 管理开发框架', value: 'manage_frameworks' },
      { name: '📦 管理项目信息', value: 'manage_project' },
      { name: '🌐 管理多语言支持', value: 'manage_i18n' },
      { name: '🔧 管理功能开关', value: 'manage_features' },
      { name: '📊 查看详细配置', value: 'view_config' },
      { name: '💾 导出配置', value: 'export_config' },
      { name: '📥 导入配置', value: 'import_config' },
      { name: '🔙 退出', value: 'exit' }
    ];

    const { action } = await inquirer.prompt([
      {
        type: 'list',
        name: 'action',
        message: '请选择操作:',
        choices,
        pageSize: 10
      }
    ]);

    await this.handleAction(action);
  }

  /**
   * 处理用户选择的操作
   */
  async handleAction(action) {
    switch (action) {
      case 'sync_all':
        await this.syncAllConfigs();
        break;
      case 'manage_languages':
        await this.manageLanguages();
        break;
      case 'manage_frameworks':
        await this.manageFrameworks();
        break;
      case 'manage_project':
        await this.manageProject();
        break;
      case 'manage_i18n':
        await this.manageI18n();
        break;
      case 'manage_features':
        await this.manageFeatures();
        break;
      case 'view_config':
        await this.viewConfig();
        break;
      case 'export_config':
        await this.exportConfig();
        break;
      case 'import_config':
        await this.importConfig();
        break;
      case 'exit':
        this.isRunning = false;
        console.log(chalk.green('👋 再见！'));
        break;
    }
  }

  /**
   * 一键同步所有配置
   */
  async syncAllConfigs() {
    console.log(chalk.blue('\n🔄 开始一键同步所有配置...'));
    
    const { confirm } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'confirm',
        message: '确定要同步所有配置文件吗？（将自动创建备份）',
        default: true
      }
    ]);

    if (!confirm) {
      console.log(chalk.yellow('❌ 操作已取消'));
      return;
    }

    try {
      const results = await this.configManager.syncToAllFiles();
      
      const successCount = results.filter(r => r.success).length;
      const failCount = results.length - successCount;
      
      console.log(chalk.green(`\n✅ 同步完成！成功: ${successCount}, 失败: ${failCount}`));
      
      if (failCount > 0) {
        console.log(chalk.yellow('⚠️ 部分文件同步失败，请检查错误信息'));
      }
      
    } catch (error) {
      console.log(chalk.red(`❌ 同步失败: ${error.message}`));
    }
    
    await this.pressAnyKey();
  }

  /**
   * 管理编程语言
   */
  async manageLanguages() {
    while (true) {
      const choices = [
        { name: '📋 查看所有语言', value: 'view' },
        { name: '✅ 启用/禁用语言', value: 'toggle' },
        { name: '➕ 添加自定义语言', value: 'add' },
        { name: '🔙 返回主菜单', value: 'back' }
      ];

      const { action } = await inquirer.prompt([
        {
          type: 'list',
          name: 'action',
          message: '语言管理:',
          choices
        }
      ]);

      switch (action) {
        case 'view':
          await this.viewLanguages();
          break;
        case 'toggle':
          await this.toggleLanguages();
          break;
        case 'add':
          await this.addCustomLanguage();
          break;
        case 'back':
          return;
      }
    }
  }

  /**
   * 查看所有语言
   */
  async viewLanguages() {
    console.log(chalk.cyan('\n📋 前端语言:'));
    this.configManager.config.languages.frontend.forEach(lang => {
      const status = lang.enabled ? chalk.green('✅') : chalk.red('❌');
      console.log(`  ${status} ${lang.name} (${lang.key}) - ${lang.description}`);
    });

    console.log(chalk.cyan('\n📋 后端语言:'));
    this.configManager.config.languages.backend.forEach(lang => {
      const status = lang.enabled ? chalk.green('✅') : chalk.red('❌');
      console.log(`  ${status} ${lang.name} (${lang.key}) - ${lang.description}`);
    });

    await this.pressAnyKey();
  }

  /**
   * 启用/禁用语言
   */
  async toggleLanguages() {
    const allLanguages = [
      ...this.configManager.config.languages.frontend.map(l => ({ ...l, type: 'frontend' })),
      ...this.configManager.config.languages.backend.map(l => ({ ...l, type: 'backend' }))
    ];

    const choices = allLanguages.map(lang => ({
      name: `${lang.enabled ? '✅' : '❌'} ${lang.name} (${lang.type})`,
      value: lang.key,
      checked: lang.enabled
    }));

    const { selectedLanguages } = await inquirer.prompt([
      {
        type: 'checkbox',
        name: 'selectedLanguages',
        message: '选择要启用的语言:',
        choices,
        pageSize: 15
      }
    ]);

    // 更新语言状态
    this.configManager.config.languages.frontend.forEach(lang => {
      lang.enabled = selectedLanguages.includes(lang.key);
    });

    this.configManager.config.languages.backend.forEach(lang => {
      lang.enabled = selectedLanguages.includes(lang.key);
    });

    this.configManager.saveConfig();
    console.log(chalk.green('✅ 语言配置已更新'));
  }

  /**
   * 管理开发框架
   */
  async manageFrameworks() {
    while (true) {
      const choices = [
        { name: '📋 查看所有框架', value: 'view' },
        { name: '✅ 启用/禁用框架', value: 'toggle' },
        { name: '🔙 返回主菜单', value: 'back' }
      ];

      const { action } = await inquirer.prompt([
        {
          type: 'list',
          name: 'action',
          message: '框架管理:',
          choices
        }
      ]);

      switch (action) {
        case 'view':
          await this.viewFrameworks();
          break;
        case 'toggle':
          await this.toggleFrameworks();
          break;
        case 'back':
          return;
      }
    }
  }

  /**
   * 查看所有框架
   */
  async viewFrameworks() {
    console.log(chalk.cyan('\n📋 前端框架:'));
    this.configManager.config.frameworks.frontend.forEach(framework => {
      const status = framework.enabled ? chalk.green('✅') : chalk.red('❌');
      console.log(`  ${status} ${framework.name} (${framework.key}) - ${framework.description}`);
    });

    console.log(chalk.cyan('\n📋 后端框架:'));
    this.configManager.config.frameworks.backend.forEach(framework => {
      const status = framework.enabled ? chalk.green('✅') : chalk.red('❌');
      console.log(`  ${status} ${framework.name} (${framework.key}) - ${framework.description}`);
    });

    if (this.configManager.config.frameworks.mobile) {
      console.log(chalk.cyan('\n📋 移动端框架:'));
      this.configManager.config.frameworks.mobile.forEach(framework => {
        const status = framework.enabled ? chalk.green('✅') : chalk.red('❌');
        console.log(`  ${status} ${framework.name} (${framework.key}) - ${framework.description}`);
      });
    }

    await this.pressAnyKey();
  }

  /**
   * 启用/禁用框架
   */
  async toggleFrameworks() {
    const allFrameworks = [
      ...this.configManager.config.frameworks.frontend.map(f => ({ ...f, type: 'frontend' })),
      ...this.configManager.config.frameworks.backend.map(f => ({ ...f, type: 'backend' })),
      ...(this.configManager.config.frameworks.mobile || []).map(f => ({ ...f, type: 'mobile' }))
    ];

    const choices = allFrameworks.map(framework => ({
      name: `${framework.enabled ? '✅' : '❌'} ${framework.name} (${framework.type})`,
      value: `${framework.type}:${framework.key}`,
      checked: framework.enabled
    }));

    const { selectedFrameworks } = await inquirer.prompt([
      {
        type: 'checkbox',
        name: 'selectedFrameworks',
        message: '选择要启用的框架:',
        choices,
        pageSize: 15
      }
    ]);

    // 更新框架状态
    ['frontend', 'backend', 'mobile'].forEach(type => {
      if (this.configManager.config.frameworks[type]) {
        this.configManager.config.frameworks[type].forEach(framework => {
          framework.enabled = selectedFrameworks.includes(`${type}:${framework.key}`);
        });
      }
    });

    this.configManager.saveConfig();
    console.log(chalk.green('✅ 框架配置已更新'));
  }

  /**
   * 管理项目信息
   */
  async manageProject() {
    while (true) {
      const project = this.configManager.config.project;
      
      console.log(chalk.cyan('\n📦 当前项目信息:'));
      console.log(`  名称: ${project.name}`);
      console.log(`  显示名称: ${project.displayName}`);
      console.log(`  版本: ${project.version}`);
      console.log(`  描述: ${project.description}`);
      console.log(`  作者: ${project.author}`);
      console.log(`  许可证: ${project.license}`);
      console.log(`  主页: ${project.homepage}`);

      const { field } = await inquirer.prompt([
        {
          type: 'list',
          name: 'field',
          message: '选择要修改的字段:',
          choices: [
            { name: '项目名称', value: 'name' },
            { name: '显示名称', value: 'displayName' },
            { name: '版本号', value: 'version' },
            { name: '项目描述', value: 'description' },
            { name: '作者', value: 'author' },
            { name: '许可证', value: 'license' },
            { name: '主页地址', value: 'homepage' },
            { name: '🔙 返回主菜单', value: 'back' }
          ]
        }
      ]);

      if (field === 'back') return;

      const { newValue } = await inquirer.prompt([
        {
          type: 'input',
          name: 'newValue',
          message: `请输入新的${field}:`,
          default: project[field]
        }
      ]);

      project[field] = newValue;
      this.configManager.saveConfig();
      console.log(chalk.green(`✅ ${field} 已更新为: ${newValue}`));
      
      await this.pressAnyKey();
    }
  }

  /**
   * 管理多语言支持
   */
  async manageI18n() {
    while (true) {
      const i18n = this.configManager.config.i18n;
      
      console.log(chalk.cyan('\n🌐 当前多语言配置:'));
      console.log(`  默认语言: ${i18n.defaultLanguage}`);
      console.log(`  支持语言: ${i18n.supportedLanguages.join(', ')}`);
      console.log(`  自动检测: ${i18n.autoDetect ? '✅ 启用' : '❌ 禁用'}`);
      console.log(`  回退语言: ${i18n.fallback}`);

      const { action } = await inquirer.prompt([
        {
          type: 'list',
          name: 'action',
          message: '多语言管理:',
          choices: [
            { name: '🔧 修改默认语言', value: 'default' },
            { name: '🌍 管理支持语言', value: 'languages' },
            { name: '🔍 切换自动检测', value: 'autodetect' },
            { name: '🔄 设置回退语言', value: 'fallback' },
            { name: '🔙 返回主菜单', value: 'back' }
          ]
        }
      ]);

      if (action === 'back') return;

      switch (action) {
        case 'default':
          await this.changeDefaultLanguage();
          break;
        case 'languages':
          await this.manageSupportedLanguages();
          break;
        case 'autodetect':
          await this.toggleAutoDetect();
          break;
        case 'fallback':
          await this.changeFallbackLanguage();
          break;
      }
    }
  }

  /**
   * 修改默认语言
   */
  async changeDefaultLanguage() {
    const availableLanguages = [
      { name: '简体中文 (zh-CN)', value: 'zh-CN' },
      { name: 'English (en-US)', value: 'en-US' },
      { name: '日本語 (ja-JP)', value: 'ja-JP' },
      { name: 'Français (fr-FR)', value: 'fr-FR' },
      { name: 'Deutsch (de-DE)', value: 'de-DE' },
      { name: 'Español (es-ES)', value: 'es-ES' },
      { name: '한국어 (ko-KR)', value: 'ko-KR' },
      { name: 'Русский (ru-RU)', value: 'ru-RU' }
    ];

    const { newDefault } = await inquirer.prompt([
      {
        type: 'list',
        name: 'newDefault',
        message: '选择新的默认语言:',
        choices: availableLanguages,
        default: this.configManager.config.i18n.defaultLanguage
      }
    ]);

    this.configManager.config.i18n.defaultLanguage = newDefault;
    this.configManager.saveConfig();
    console.log(chalk.green(`✅ 默认语言已更新为: ${newDefault}`));
    
    await this.pressAnyKey();
  }

  /**
   * 管理支持的语言
   */
  async manageSupportedLanguages() {
    const availableLanguages = [
      { name: '简体中文 (zh-CN)', value: 'zh-CN' },
      { name: 'English (en-US)', value: 'en-US' },
      { name: '日本語 (ja-JP)', value: 'ja-JP' },
      { name: 'Français (fr-FR)', value: 'fr-FR' },
      { name: 'Deutsch (de-DE)', value: 'de-DE' },
      { name: 'Español (es-ES)', value: 'es-ES' },
      { name: '한국어 (ko-KR)', value: 'ko-KR' },
      { name: 'Русский (ru-RU)', value: 'ru-RU' }
    ];

    const { selectedLanguages } = await inquirer.prompt([
      {
        type: 'checkbox',
        name: 'selectedLanguages',
        message: '选择要支持的语言:',
        choices: availableLanguages,
        default: this.configManager.config.i18n.supportedLanguages
      }
    ]);

    if (selectedLanguages.length === 0) {
      console.log(chalk.red('❌ 至少需要选择一种语言'));
      return;
    }

    this.configManager.config.i18n.supportedLanguages = selectedLanguages;
    
    // 确保默认语言在支持列表中
    if (!selectedLanguages.includes(this.configManager.config.i18n.defaultLanguage)) {
      this.configManager.config.i18n.defaultLanguage = selectedLanguages[0];
      console.log(chalk.yellow(`⚠️ 默认语言已自动调整为: ${selectedLanguages[0]}`));
    }

    // 确保回退语言在支持列表中
    if (!selectedLanguages.includes(this.configManager.config.i18n.fallback)) {
      this.configManager.config.i18n.fallback = selectedLanguages[0];
      console.log(chalk.yellow(`⚠️ 回退语言已自动调整为: ${selectedLanguages[0]}`));
    }

    this.configManager.saveConfig();
    console.log(chalk.green(`✅ 支持语言已更新: ${selectedLanguages.join(', ')}`));
    
    await this.pressAnyKey();
  }

  /**
   * 切换自动检测
   */
  async toggleAutoDetect() {
    const current = this.configManager.config.i18n.autoDetect;
    
    const { enable } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'enable',
        message: '是否启用语言自动检测?',
        default: current
      }
    ]);

    this.configManager.config.i18n.autoDetect = enable;
    this.configManager.saveConfig();
    
    const status = enable ? '启用' : '禁用';
    console.log(chalk.green(`✅ 语言自动检测已${status}`));
    
    await this.pressAnyKey();
  }

  /**
   * 修改回退语言
   */
  async changeFallbackLanguage() {
    const supportedLanguages = this.configManager.config.i18n.supportedLanguages;
    
    const choices = supportedLanguages.map(lang => {
      const langNames = {
        'zh-CN': '简体中文',
        'en-US': 'English',
        'ja-JP': '日本語',
        'fr-FR': 'Français',
        'de-DE': 'Deutsch',
        'es-ES': 'Español',
        'ko-KR': '한국어',
        'ru-RU': 'Русский'
      };
      return {
        name: `${langNames[lang] || lang} (${lang})`,
        value: lang
      };
    });

    const { newFallback } = await inquirer.prompt([
      {
        type: 'list',
        name: 'newFallback',
        message: '选择回退语言:',
        choices,
        default: this.configManager.config.i18n.fallback
      }
    ]);

    this.configManager.config.i18n.fallback = newFallback;
    this.configManager.saveConfig();
    console.log(chalk.green(`✅ 回退语言已更新为: ${newFallback}`));
    
    await this.pressAnyKey();
  }

  /**
   * 管理功能开关
   */
  async manageFeatures() {
    while (true) {
      const features = this.configManager.config.features;
      
      console.log(chalk.cyan('\n⚙️ 当前功能状态:'));
      Object.keys(features).forEach(key => {
        console.log(`  ${features[key] ? '✅' : '❌'} ${key}`);
      });

      const { action } = await inquirer.prompt([
        {
          type: 'list',
          name: 'action',
          message: '功能管理:',
          choices: [
            { name: '🔧 修改功能开关', value: 'modify' },
            { name: '🔙 返回主菜单', value: 'back' }
          ]
        }
      ]);

      if (action === 'back') return;

      const choices = Object.keys(features).map(key => ({
        name: `${features[key] ? '✅' : '❌'} ${key}`,
        value: key,
        checked: features[key]
      }));

      const { selectedFeatures } = await inquirer.prompt([
        {
          type: 'checkbox',
          name: 'selectedFeatures',
          message: '选择要启用的功能:',
          choices
        }
      ]);

      // 更新功能状态
      Object.keys(features).forEach(key => {
        features[key] = selectedFeatures.includes(key);
      });

      this.configManager.saveConfig();
      console.log(chalk.green('✅ 功能配置已更新'));
      
      await this.pressAnyKey();
    }
  }

  /**
   * 查看详细配置
   */
  async viewConfig() {
    while (true) {
      const { action } = await inquirer.prompt([
        {
          type: 'list',
          name: 'action',
          message: '配置查看:',
          choices: [
            { name: '📊 查看完整配置', value: 'view' },
            { name: '🔙 返回主菜单', value: 'back' }
          ]
        }
      ]);

      if (action === 'back') return;

      console.log(chalk.cyan('\n📊 详细配置信息:'));
      console.log(JSON.stringify(this.configManager.config, null, 2));
      await this.pressAnyKey();
    }
  }

  /**
   * 导出配置
   */
  async exportConfig() {
    while (true) {
      const { action } = await inquirer.prompt([
        {
          type: 'list',
          name: 'action',
          message: '配置导出:',
          choices: [
            { name: '📤 导出配置文件', value: 'export' },
            { name: '🔙 返回主菜单', value: 'back' }
          ]
        }
      ]);

      if (action === 'back') return;

      const { filename } = await inquirer.prompt([
        {
          type: 'input',
          name: 'filename',
          message: '请输入导出文件名:',
          default: `config-export-${new Date().toISOString().split('T')[0]}.json`
        }
      ]);

      try {
        const exportPath = path.join(process.cwd(), filename);
        fs.writeFileSync(exportPath, JSON.stringify(this.configManager.config, null, 2), 'utf8');
        console.log(chalk.green(`✅ 配置已导出到: ${exportPath}`));
      } catch (error) {
        console.log(chalk.red(`❌ 导出失败: ${error.message}`));
      }
      
      await this.pressAnyKey();
    }
  }

  /**
   * 导入配置
   */
  async importConfig() {
    while (true) {
      const { action } = await inquirer.prompt([
        {
          type: 'list',
          name: 'action',
          message: '配置导入:',
          choices: [
            { name: '📥 导入配置文件', value: 'import' },
            { name: '🔙 返回主菜单', value: 'back' }
          ]
        }
      ]);

      if (action === 'back') return;

      const { filepath } = await inquirer.prompt([
        {
          type: 'input',
          name: 'filepath',
          message: '请输入配置文件路径:'
        }
      ]);

      try {
        if (!fs.existsSync(filepath)) {
          throw new Error('文件不存在');
        }

        const importedConfig = JSON.parse(fs.readFileSync(filepath, 'utf8'));
        
        const { confirm } = await inquirer.prompt([
          {
            type: 'confirm',
            name: 'confirm',
            message: '确定要导入此配置吗？（当前配置将被覆盖）',
            default: false
          }
        ]);

        if (confirm) {
          this.configManager.config = importedConfig;
          this.configManager.saveConfig();
          console.log(chalk.green('✅ 配置导入成功'));
        } else {
          console.log(chalk.yellow('❌ 导入已取消'));
        }
      } catch (error) {
        console.log(chalk.red(`❌ 导入失败: ${error.message}`));
      }
      
      await this.pressAnyKey();
    }
  }

  /**
   * 等待用户按键
   */
  async pressAnyKey() {
    await inquirer.prompt([
      {
        type: 'input',
        name: 'continue',
        message: '按回车键继续...'
      }
    ]);
  }
}

// 如果直接运行此文件，启动CLI
if (require.main === module) {
  const cli = new UnifiedConfigCLI();
  cli.start().catch(error => {
    console.error(chalk.red(`❌ CLI启动失败: ${error.message}`));
    process.exit(1);
  });
}

module.exports = UnifiedConfigCLI;